define(function (require) {

    require('../../../c/base/index');

    require('../../../c/nav/index');


    var firstTime = true;

    var dataRight = {
        init: function () {
            //初始化菜单选中效果
            $(".fa-circle-o").each(function () {
                if ($(this).parents("a").text() == "CRM数据白名单管理") {
                    $(this).parents("a").parents("li").addClass("active");
                }
            });
            this.initTable();
            this.initValidator();
            this.bindEvent();
        },
        /**
         * 执行查询操作.
         */
        doSearch: function () {
            $('#table').DataTable().ajax.reload();
        },
        /**
         * 初始化列表
         */
        initTable: function () {
            var self = this;
            $("#table").dataTable({
                "oLanguage": CRM.pageConfig,
                "sScrollX": "100%",   //表格的宽度
                "sScrollXInner": "100%",   //表格的内容宽度
                "bScrollCollapse": true,  //当显示的数据不足以支撑表格的默认的高度时，依然显示纵向的滚动条。(默认是false)
                "bPaginate": false,  //是否显示分页
                "bLengthChange": false,  //每页显示的记录数
                "bFilter": false, //搜索栏
                "bSort": false, //是否支持排序功能
                "bInfo": true, //显示表格信息
                "bAutoWidth": false,  //自适应宽度
                "bServerSide": true,//开启服务端处理
                "sAjaxSource": "../../crm/listDataRightList",
                "fnInitComplete": function () {
                    this.fnAdjustColumnSizing(true);
                },
                "fnServerData": function (sSource, aoData, fnCallback) {
                    if (firstTime) {
                        firstTime = false;
                        return;
                    }
                    var dataString, _data = {};
                    $($("#J_Search").serializeArray()).each(function () {
                        _data[this.name] = this.value;
                    });
                    dataString = JSON.stringify(_data);
                    CRM.request({
                        "type": 'POST',
                        "url": sSource,
                        "dataType": "json",
                        contentType: "application/json",
                        xhrFields: {
                            withCredentials: true
                        },
                        "data": dataString,
                        contentType: "application/json",
                        "success": function (req) {
                            if (req.status) {
                                var resultData = CRM.getDataTabelDtaObject();
                                if (req.entry) {
                                    resultData.iTotalDisplayRecords = req.entry.length;
                                    resultData.iTotalRecords = req.entry.length;
                                    for (var length in req.entry) {
                                        resultData.aaData.push([
                                            req.entry[length].mobile,
                                            req.entry[length].right_type,
                                            req.entry[length].right_value,
                                            req.entry[length]]);
                                    }
                                } else {
                                    CRM.showDialog(req.message);
                                }
                                fnCallback(resultData);
                            } else {
                                CRM.showDialog(req.message);
                            }
                        }
                    });
                },
                "aaSorting": [[1, "asc"]],  //给列表排序 ，第一个参数表示数组 (由0开始)。1 表示Browser列。第二个参数为 desc或是asc
                "aoColumns": [
                    {
                        "sTitle": "用户号码",
                        "bSortable": true
                    },
                    {
                        "sTitle": "白名单类型",
                        "bSortable": true
                    },
                    {
                        "sTitle": "权限值",
                        "bSortable": true
                    },
                    {
                        "sTitle": "操作",
                        "bSortable": false,
                        "mRender": function (data) {
                            var html = '<button type="button" class="btn btn-primary" onclick=javascript:openModify(\'' + JSON.stringify(data) + '\')>修改</button> ';
                            html += '<button type="button" class="btn btn-danger" onclick="javascript:deleteData(\'' + data.id + '\')">删除</button>';
                            return html;
                        }
                    }

                ], //列设置，表有几列，数组就有几项
                "bStateSave": true, //保存状态到cookie *************** 很重要 ， 当搜索的时候页面一刷新会导致搜索的消失。使用这个属性就可避免了
                "sPaginationType": "full_numbers" //分页，一共两种样式，full_numbers和two_button(默认)

            });
        },
        /**
         * 表单验证初始化
         */
        initValidator: function () {
            $('#J_Search').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {}
            });
            $('#modify_form').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    modify_mobile: {
                        message: '输入错误',
                        validators: {
                            phone: {
                                country: 'CN',
                                message: '请输入正确的号码'
                            }
                        }
                    }
                }

            });

        },
        /**
         * 打开编辑窗口
         * @param dataStr
         */
        openModify: function (dataStr) {
            $("#modify_id").val("");
            $("#modify_mobile").val("");
            $("#modify_rightType").val("");
            $("#modify_rightValue").val("");
            if(dataStr){
                eval("var _data=" + dataStr);
                $("#modify_id").val(_data.id);
                $("#modify_mobile").val(_data.mobile);
                $("#modify_rightType").val(_data.right_type);
                $("#modify_rightValue").val(_data.right_value);
            }
            $('#modify_dialog').modal('show');
            $('#modify_dialog').on('shown.bs.modal', function (e) {
                $("#modify_form").data('bootstrapValidator').resetForm();
            });
        },
        /**
         * 保存
         */
        save:function(){
            var self = this;
            $("#modify_form").data('bootstrapValidator').resetForm();
            $("#modify_form").data('bootstrapValidator').validate();
            if ($("#modify_form").data('bootstrapValidator').isValid()) {
                var _url = "../../crm/addDataRight";
                if($("#modify_id").val()){
                    _url = "../../crm/updateDataRight";
                }
                var dataString, _data = {};
                $($("#modify_form").serializeArray()).each(function () {
                    _data[this.name.replace("modify_","")] = this.value;
                });
                dataString = JSON.stringify(_data);
                CRM.request({
                    "type": 'POST',
                    "url": _url,
                    "dataType": "json",
                    contentType: "application/json",
                    "data": dataString,
                    "success": function (req) {
                        if (req.status) {
                            $('#modify_dialog').modal('hide');
                            CRM.showDialog("保存成功！");
                            self.doSearch();
                        } else {
                            CRM.showDialog(req.message);
                        }
                    }
                });
            }
        },
        /**
         * 删除
         * @param id
         */
        deleteData:function(id){
            if(confirm("确定删除？该操作不能恢复")){
                CRM.request({
                    "type": 'POST',
                    "url": "../../crm/deleteDataRight",
                    "dataType": "json",
                    contentType: "application/json",
                    "data": JSON.stringify({id:id}),
                    "success": function (req) {
                        if (req.status) {
                            self.doSearch();
                        } else {
                            CRM.showDialog(req.message);
                        }
                    }
                });
            }


        },
        bindEvent: function () {
            var self = this;
            $("#search_btn").on('click', function () {
                self.doSearch();
            });
            $("#add_btn").on('click', function () {
                self.openModify();
            });

        }
    };

    window.doSearch = $.proxy(dataRight.doSearch, dataRight);
    window.openModify = $.proxy(dataRight.openModify, dataRight);
    window.save = $.proxy(dataRight.save, dataRight);
    window.deleteData = $.proxy(dataRight.deleteData, dataRight);

    dataRight.init();
});